/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.contentResource.image;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.service.core.ContentResourceManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.core.ImageForm;
import com.blandware.atleap.webapp.form.core.UploadContentResourceForm;
import com.blandware.atleap.webapp.util.core.*;
import com.blandware.atleap.search.SearchManager;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.imageio.IIOImage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

/**
 * <p>Updates image
 * </p>
 * <p><a href="UpdateImageAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.27 $ $Date: 2007/12/18 11:43:31 $
 * @struts.action path="/core/contentResource/image/update"
 * name="imageForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-contentResource-update"
 * @struts.action-forward name="inputForward"
 * path=".core.contentResource.image.update"
 * @struts.action-forward name="updateContentResource"
 * path="/core/contentResource/callUpdate.do"
 * @struts.action-forward name="listContentResources"
 * path="/core/contentResource/list.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateImage"
 * path="/core/contentResource/callUpdate.do"
 * redirect="false"
 * @struts.action-forward name="viewLinkedObjects"
 * path="/core/linkedObjects/view.do"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/contentResource/list.do"
 */
public final class UpdateImageAction extends BaseAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        String requestUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);

        // flag shows whether to force changing of URI if there're some
        // linked objects
        boolean force = "true".equalsIgnoreCase(request.getParameter("force"));

        ImageForm imageForm;
        if (force) {
            imageForm = (ImageForm) session.getAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY);
        } else {
            imageForm = (ImageForm) form;
        }

		UploadContentResourceForm uploadContentResourceForm = (UploadContentResourceForm) session
                .getAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
		FormFile formFile = null;
		if ( uploadContentResourceForm != null ) {
			formFile = uploadContentResourceForm.getFile();
		}

		Long imageId;
		if ( !GenericValidator.isBlankOrNull(imageForm.getId()) ) {
			imageId = Long.valueOf(imageForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing image ID. Returning to list");
			}
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}


        if (isBackPressed(request)) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
			request.setAttribute(WebappConstants.CONTENT_RESOURCE_ID_KEY, imageId);
			return mapping.findForward("updateContentResource");
		}

		if ( isCancelled(request) ) {
			if ( formFile != null ) {
				formFile.destroy();
			}
			session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

		ContentResourceManager contentResourceManager = (ContentResourceManager) getBean(Constants.CONTENT_RESOURCE_MANAGER_BEAN);
		ContentImage image = contentResourceManager.retrieveContentImage(imageId);

		if ( image == null ) {
			// image not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("imageNotFound", new ActionMessage("core.contentResource.image.errors.notFound"));
			saveErrors(request, errors);
            if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
                session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
                return new ActionForward(requestUrl, true);
            }
            return mapping.findForward("listContentResources");
		}

        String uri = Constants.RESOURCES_URI_PREFIX + imageForm.getUri();

		String oldUri = image.getUri();

        if (!oldUri.equals(uri)) {
            // check whether there is already another content resource with this URI
            ContentResource oldResource = contentResourceManager.findContentResourceByUri(uri);
            if (oldResource != null) {
                // content resource already exists
                ActionMessages errors = new ActionMessages();
                errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
                saveErrors(request, errors);
                saveToken(request);
                return mapping.getInputForward();
            }
        }

        boolean uriChanged = !oldUri.equals(uri);
        if (!force && image.isInUse() && uriChanged ) {
            // trying to change URI of used content resource - display warning
            String action = mapping.findForward("listContentResources").getPath();
            String redirectUrl = WebappUtil.getActionMappingURL(action, null, request, WebappConstants.URL_TYPE_DOMAIN_RELATIVE);
            session.setAttribute(WebappConstants.CONTENT_RESOURCE_FORM_KEY, imageForm);
            ActionMessages messages = new ActionMessages();
            messages.add("changeUriWarning", new ActionMessage("core.contentResource.messages.changeUriWarning"));
            if (image.doUnmodifiableLinkedObjectsExist()) {
                messages.add("unmodifiableLinkedObjectsWarning", new ActionMessage("core.contentResource.messages.unmodifiableLinkedObjectsWarning"));
            }
            saveMessages(request, messages);

            LinkedObjectsInfoContainer container = new LinkedObjectsInfoContainer();
            container.setRedirectUrl(redirectUrl);
            container.setNewUri(uri);
            container.setWidth(imageForm.getWidth());
            container.setHeight(imageForm.getHeight());
            container.setUpdateAction(mapping.getPath());
            container.setObjectId(image.getId());
            container.setObjectType(LinkedObjectsInfoContainer.TYPE_RESOURCE);
            session.setAttribute(WebappConstants.LINKED_OBJECTS_INFO_CONTAINER_KEY, container);

            return mapping.findForward("viewLinkedObjects");
        }

		WebappUtil.copyProperties(image, imageForm, request);
        WebappUtil.copyFieldValue(image.getDescription(), imageForm.getDescriptionMap());

        //setup uri
		image.setUri(uri);

        // remove links to this resource from unmodifiable menu items
        if (uriChanged) {
            for (Iterator i = image.getLinkedMenuItems().iterator(); i.hasNext();) {
                MenuItem menuItem = (MenuItem) i.next();
                if (!menuItem.isDynamic()) {
                    i.remove();
                }
            }
        }

		ResourceTypesManager resourceTypesManager = ResourceTypesManager.getInstance(
                session.getServletContext());
		CacheUtil cacheUtil = CacheUtil.getInstance(request);

		byte[] imageData;
		String mimeType;
        int oldWidth = image.getWidth().intValue();
        int oldHeight = image.getHeight().intValue();

		if ( formFile != null && formFile.getFileName() != null && formFile.getFileName().trim().length() > 0 ) {
			//if image updated
			imageData = formFile.getFileData();
			mimeType = resourceTypesManager.getMimeTypeByFileName(formFile.getFileName());
			IIOImage source = ImageUtil.decodeImage(imageData, mimeType);
			image.setWidth(new Integer(source.getRenderedImage().getWidth()));
			image.setHeight(new Integer(source.getRenderedImage().getHeight()));
			image.setSize(new Long(imageData.length));
		} else {
			imageData = image.getResourceData().getData();
			mimeType = image.getMimeType();
		}

		try {
			if ( imageForm.isScale() ) {
				IIOImage source = ImageUtil.decodeImage(imageData, mimeType);
				int maxWidth = Integer.parseInt(imageForm.getScaleWidth());
				int maxHeight = Integer.parseInt(imageForm.getScaleHeight());
				IIOImage scaled = ImageUtil.scaleToRectangle(source, maxWidth, maxHeight);
				try {
					imageData = ImageUtil.encodeImage(scaled, mimeType);
				} catch ( IllegalArgumentException ex ) {
					//cannot encode into original format, try to default
					mimeType = resourceTypesManager.getDefaultMimeType(image.getType());
					imageData = ImageUtil.encodeImage(scaled, mimeType);
				}
                image.setWidth(new Integer(scaled.getRenderedImage().getWidth()));
                image.setHeight(new Integer(scaled.getRenderedImage().getHeight()));
                image.setSize(new Long(imageData.length));
			}

            int newWidth = image.getWidth().intValue();
            int newHeight = image.getHeight().intValue();
            // this flag is needed to determine whether to recache/reindex CFVs
            // that are linked to this image because its sizes will be changed
            // in <img> tags
            boolean sizesChanged = oldWidth != newWidth || oldHeight != newHeight;

			ResourceData resourceData = image.getResourceData();
			if ( resourceData != null ) {
				resourceData.setData(imageData);
			} else {
				resourceData = new ResourceData(imageData);
			}
			image.setMimeType(mimeType);
			contentResourceManager.updateContentImage(image, resourceData);

			//flush cache
			cacheUtil.flushResourceCache(oldUri);

			//put into cache
			CacheUtil.ResourceData rd = new CacheUtil.ResourceData(imageData, mimeType, WebappUtil.rolesToString(image.getRoles()), image.getLastUpdatedDatetime().getTime());
			cacheUtil.putResourceInCache(rd, uri);

            if (force) {
                // flush cache related to menu items
                cacheUtil.flushMenuCache();
            }

            if (force || sizesChanged) {
                // reindex and update cache for linked objects, because they
                // were changed
                SearchManager searchManager = SearchManager.getInstance(session.getServletContext());

                // put linked values in cache and into search index
                List linkedContentFieldValues = image.getLinkedContentFieldValues();
                Set owners = new HashSet();
                for (Iterator i = linkedContentFieldValues.iterator(); i.hasNext();) {
                    ContentFieldValue fieldValue = (ContentFieldValue) i.next();
                    ContentField field = fieldValue.getContentField();
                    Localizable owner = field.getOwner();
                    // put owner to set of owners to cache/reindex them later
                    owners.add(owner);

                    String localeIdentifier = fieldValue.getContentLocale().getIdentifier();

                    byte fieldType = field.getType();
                    String content;

                    if (fieldType == ContentField.LINE_TYPE) {
                        content = fieldValue.getSimpleValue();
                    } else {
                        content = ConvertUtil.convertToString(fieldValue.getValue());
                    }
                    if ( owner instanceof Page ) {
                        Page page = (Page) owner;
                        CacheUtil.CFVData cfvData = new CacheUtil.CFVData(content, field.getId(), field.getType(), fieldValue.getId(), owner.getId());
                        cacheUtil.putPageFieldValueInCache(cfvData, page.getUri(), field.getIdentifier(), localeIdentifier);
                    }
                }

                // process owners
                for (Iterator i = owners.iterator(); i.hasNext();) {
                    Localizable owner = (Localizable) i.next();
                    if ( owner instanceof Layout ) {
                        Layout layout = (Layout) owner;
                        cacheUtil.flushLayoutFieldValueCache(layout.getDefinition());

                        //TODO: add into search index for every content page of the layout.
                        //TODO: add into index action pages
                        List contentPages = layout.getContentPages();
                        for ( int j = 0; j < contentPages.size(); j++ ) {
                            ContentPage cp = (ContentPage) contentPages.get(j);
                            searchManager.reIndexPage(cp, request);
                            cacheUtil.updateContentPageLastModifiedInCache(cp.getUri());
                        }

                    } else if ( owner instanceof Page ) {
                        Page page = (Page) owner;
                        searchManager.reIndexPage(page, request);
                        if ( page instanceof ContentPage ) {
                            cacheUtil.updateContentPageLastModifiedInCache(page.getUri());
                        }
                    }
                }
            }

		} catch ( BeanAlreadyExistsException e ) {
			ActionMessages errors = new ActionMessages();
			errors.add("contentResourceAlreadyExists", new ActionMessage("core.contentResource.errors.alreadyExists"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		} catch ( ObjectOptimisticLockingFailureException e ) {
			// image was updated or deleted by another transaction
			ActionMessages errors = new ActionMessages();
			errors.add("updateFailed", new ActionMessage("core.contentResource.image.errors.updateFailed"));
			saveErrors(request, errors);
			return mapping.findForward("callUpdateImage");
		}

		if ( formFile != null ) {
			formFile.destroy();
		}
		session.removeAttribute(WebappConstants.UPLOAD_CONTENT_RESOURCE_FORM_KEY);

        if ( !GenericValidator.isBlankOrNull(requestUrl) ) {
            session.removeAttribute(WebappConstants.REDIRECT_URL_KEY);
            return new ActionForward(requestUrl, true);
        }
        return mapping.findForward("listContentResources");
	}
}